package com.bdqn.controller;

import com.bdqn.common.Constants;
import com.bdqn.pojo.DevUser;
import com.bdqn.service.DevUserService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * DevUserController
 *
 * @author LILIBO
 * @since 2022-01-07
 */
@Controller
@RequestMapping("/dev")
public class DevLoginController {

    private Logger logger = Logger.getLogger(DevLoginController.class);

    @Resource
    private DevUserService devUserService;

    /**
     * 跳转到登录页
     */
    @GetMapping("/login")
    public String toLogin() {
        return "devlogin";
    }

    /**
     * 跳转到后台页
     */
    @GetMapping("/main")
    public String toDevMain() {
        return "developer/main";
    }

    /**
     * 登录验证
     */
    @PostMapping("/doLogin")
    public String doLogin(Model model, HttpSession session, String devCode, String devPassword) {
        logger.debug("doLogin");
        DevUser devUser = devUserService.findDevUser(devCode, devPassword);
        if (devUser == null) {
            model.addAttribute("error", "账号或密码错误");
            return "devlogin";
        }
        // 登录成功，将用户对象存入Session作用域
        session.setAttribute(Constants.DEV_USER_SESSION, devUser);
        return "redirect:/dev/main";
    }

    /**
     * 退出登录
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        logger.debug("logout");
        // 清空Session中用户对象
        session.removeAttribute(Constants.DEV_USER_SESSION);
        session.invalidate(); // 销毁Session
        // 重定向到登录页面
        return "redirect:/dev/login";
    }

}
